package com.naja.event.tracking.extract.xxl;

import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.naja.event.tracking.extract.dto.IncrExtractBaseEventToBizDto;
import com.naja.event.tracking.extract.service.TEventTraceAggregatedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 定时任务
 **/
@Component
public class ExtractBaseEventToBizTaskJobHandler {
    private static final Logger logger = LoggerFactory.getLogger(ExtractBaseEventToBizTaskJobHandler.class);

    @Autowired
    TEventTraceAggregatedService tEventTraceAggregatedService;

    /**
     * 任务执行
     */
    @XxlJob("incrExtractBaseEventToBizJob")
    public ReturnT<String> incrExtractBaseEventToBiz(String param) {
        logger.info("定时增量抽取基础事件到业务事件开始,参数=>{}", param);
        try {
            IncrExtractBaseEventToBizDto body = null;
            if (StringUtils.hasText(param)) {
                body = JSONObject.parseObject(param, IncrExtractBaseEventToBizDto.class);
            }
            if (body == null) {
                body = new IncrExtractBaseEventToBizDto();
            }
            Long secondlAgo = body.getSecondlAgo();
            if (secondlAgo != null) {
                Date agoDate = new Date(System.currentTimeMillis() - secondlAgo * 1000);
                if (body.getStartTime() == null || agoDate.before(body.getStartTime())) {
                    body.setStartTime(agoDate);
                }
            }
            String[] observers = null;
            if (body.getObservers() != null && !body.getObservers().isEmpty()) {
                observers = new String[body.getObservers().size()];
                body.getObservers().toArray(observers);
            }
            tEventTraceAggregatedService.incrExtractBaseEventToBiz(body.getStartTime(), observers);
        } catch (Exception e) {
            logger.error("定时增量抽取基础事件到业务事件异常,参数=>{}", param, e);
            return ReturnT.FAIL;
        }finally {
            logger.info("定时增量抽取基础事件到业务事件结束,参数=>{}", param);
        }
        return ReturnT.SUCCESS;
    }

}
